package cn.powerone.scm.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import cn.powerone.common.utils.DateUtils;
import cn.powerone.scm.domain.*;
import cn.powerone.scm.service.IScmCustomerQuotesService;
import cn.powerone.scm.service.IScmProjectsService;
import org.apache.poi.hpsf.Decimal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import cn.powerone.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import cn.powerone.scm.mapper.ScmEstimateQuotesMapper;
import cn.powerone.scm.service.IScmEstimateQuotesService;

/**
 * 客户报价单Service业务层处理
 * 
 * @author PowerOne
 * @date 2025-07-02
 */
@Service
public class ScmEstimateQuotesServiceImpl implements IScmEstimateQuotesService 
{
    @Autowired
    private ScmEstimateQuotesMapper scmEstimateQuotesMapper;
    @Autowired
    private IScmCustomerQuotesService scmCustomerQuotesService;
    @Autowired
    private IScmProjectsService scmProjectsService;

    /**
     * 查询客户报价单
     * 
     * @param id 客户报价单主键
     * @return 客户报价单
     */
    @Override
    public ScmEstimateQuotes selectScmEstimateQuotesById(Long id)
    {
        return scmEstimateQuotesMapper.selectScmEstimateQuotesById(id);
    }

    /**
     * 查询客户报价单列表
     * 
     * @param scmEstimateQuotes 客户报价单
     * @return 客户报价单
     */
    @Override
    public List<ScmEstimateQuotes> selectScmEstimateQuotesList(ScmEstimateQuotes scmEstimateQuotes)
    {
        return scmEstimateQuotesMapper.selectScmEstimateQuotesList(scmEstimateQuotes);
    }

    /**
     * 新增客户报价单
     * 
     * @param scmEstimateQuotes 客户报价单
     * @return 结果
     */
    @Transactional
    @Override
    public int insertScmEstimateQuotes(ScmEstimateQuotes scmEstimateQuotes)
    {
        scmEstimateQuotes.setCreateTime(DateUtils.getNowDate());
        int rows = scmEstimateQuotesMapper.insertScmEstimateQuotes(scmEstimateQuotes);
        insertScmEstimateQuoteItems(scmEstimateQuotes);
        return rows;
    }

    /**
     * 修改客户报价单
     * 
     * @param scmEstimateQuotes 客户报价单
     * @return 结果
     */
    @Transactional
    @Override
    public int updateScmEstimateQuotes(ScmEstimateQuotes scmEstimateQuotes)
    {
        scmEstimateQuotes.setUpdateTime(DateUtils.getNowDate());
        scmEstimateQuotesMapper.deleteScmEstimateQuoteItemsByQuoteId(scmEstimateQuotes.getId());
        insertScmEstimateQuoteItems(scmEstimateQuotes);
        return scmEstimateQuotesMapper.updateScmEstimateQuotes(scmEstimateQuotes);
    }

    /**
     * 批量删除客户报价单
     * 
     * @param ids 需要删除的客户报价单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteScmEstimateQuotesByIds(Long[] ids)
    {
        scmEstimateQuotesMapper.deleteScmEstimateQuoteItemsByQuoteIds(ids);
        return scmEstimateQuotesMapper.deleteScmEstimateQuotesByIds(ids);
    }

    /**
     * 删除客户报价单信息
     * 
     * @param id 客户报价单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteScmEstimateQuotesById(Long id)
    {
        scmEstimateQuotesMapper.deleteScmEstimateQuoteItemsByQuoteId(id);
        return scmEstimateQuotesMapper.deleteScmEstimateQuotesById(id);
    }

    /**
     * 根据询价单ID查询客户报价单
     *
     * @param inquiryId 询价单ID
     * @return 客户报价单
     */
    @Override
    public ScmEstimateQuotes selectScmEstimateQuotesBySupplierQuoteId(Long supplierQuoteId) {
        return scmEstimateQuotesMapper.selectScmEstimateQuotesBySupplierQuoteId(supplierQuoteId);
    }

    /**
     * 新增估算报价单额外明细信息
     * 
     * @param scmEstimateQuotes 客户报价单对象
     */
    public void insertScmEstimateQuoteItems(ScmEstimateQuotes scmEstimateQuotes)
    {
        List<ScmEstimateQuoteItems> scmEstimateQuoteItemsList = scmEstimateQuotes.getScmEstimateQuoteItemsList();
        Long id = scmEstimateQuotes.getId();
        if (StringUtils.isNotNull(scmEstimateQuoteItemsList))
        {
            List<ScmEstimateQuoteItems> list = new ArrayList<ScmEstimateQuoteItems>();
            for (ScmEstimateQuoteItems scmEstimateQuoteItems : scmEstimateQuoteItemsList)
            {
                scmEstimateQuoteItems.setQuoteId(id);
                list.add(scmEstimateQuoteItems);
            }
            if (list.size() > 0)
            {
                scmEstimateQuotesMapper.batchScmEstimateQuoteItems(list);
            }
        }
    }

    /**
     * 批量更新客户报价单状态
     *
     * @param ids 需要更新的客户报价单主键
     * @return 结果
     */
    @Override
    public int updateStatusScmSupplierQuotesByIds(Long[] ids, ScmEstimateQuotes scmEstimateQuotes) {
        if (scmEstimateQuotes.getStatus() != 1 && scmEstimateQuotes.getStatus() != 2 && scmEstimateQuotes.getStatus() != 3){
            return 0;
        }
        ScmProjects scmProjects = null;
        //遍历ids， 并从数据库中查询，获取对应的研讨报价单
        ScmEstimateQuotes tempQuote;
        ScmCustomerQuotes scmCustomerQuotes;
        BigDecimal convertRate = BigDecimal.valueOf(1L);
        int rows = 0;
        for (Long id : ids) {
            tempQuote = scmEstimateQuotesMapper.selectScmEstimateQuotesById(id);
            // 更新报价单状态
            if (tempQuote == null){
                continue;
            }
            if (scmProjects == null){ // 获取Project ,赋值currency
                scmProjects = scmProjectsService.selectScmProjectsByProjectId(tempQuote.getProjectId());
                if (scmProjects != null && scmProjects.getSupplierCurrencyRate() != null &&
                    scmProjects.getSupplierCurrencyRate().compareTo(BigDecimal.ZERO) != 0 && scmProjects.getCustomerCurrencyRate() != null && scmProjects.getCustomerCurrencyRate().compareTo(BigDecimal.ZERO) != 0) {
                    convertRate = BigDecimal.ONE
                            .divide(scmProjects.getSupplierCurrencyRate(), 5, RoundingMode.HALF_UP)  // 先做除法，保留5位精度
                            .multiply(scmProjects.getCustomerCurrencyRate())                           // 再做乘法
                            .setScale(5, RoundingMode.HALF_UP);
                }else {
                    // 根据业务需求处理异常情况
                    convertRate = BigDecimal.ONE; // 或抛出异常
                }
            }
            if (scmProjects == null){
                continue;
            }
            tempQuote.setStatus(scmEstimateQuotes.getStatus());
            tempQuote.setStatusReason(scmEstimateQuotes.getStatusReason());
            rows  += scmEstimateQuotesMapper.updateScmEstimateQuotes(tempQuote);

            scmCustomerQuotes = scmCustomerQuotesService.selectScmCustomerQuotesBySupplierQuoteId(tempQuote.getSupplierQuoteId());
            // 如果报价单状态为1，则生成对应的ScmEstimateQuotes
            if (scmEstimateQuotes.getStatus() == 1){
                if (scmCustomerQuotes == null){
                    scmCustomerQuotes = new ScmCustomerQuotes();
                    scmCustomerQuotes.setProjectId(tempQuote.getProjectId());
                    scmCustomerQuotes.setProductId(tempQuote.getProductId());
                    scmCustomerQuotes.setProjectProductId(tempQuote.getProjectProductId());
                    scmCustomerQuotes.setDrawingNumber(tempQuote.getDrawingNumber());
                    scmCustomerQuotes.setInternalVersion(tempQuote.getInternalVersion());
                    scmCustomerQuotes.setSupplierId(tempQuote.getSupplierId());
                    scmCustomerQuotes.setSupplierQuoteId(tempQuote.getSupplierQuoteId());
                    scmCustomerQuotes.setSupplierName( tempQuote.getSupplierName());
                    scmCustomerQuotes.setQuoteDate(tempQuote.getQuoteDate());
                    scmCustomerQuotes.setDrawingMaterial(tempQuote.getDrawingMaterial());
                    scmCustomerQuotes.setMaterial(tempQuote.getMaterial());
                    scmCustomerQuotes.setInflamingRetardingLevel(tempQuote.getInflamingRetardingLevel());
                    scmCustomerQuotes.setTaxIncluded(tempQuote.getTaxIncluded());
                    scmCustomerQuotes.setFreightIncluded(tempQuote.getFreightIncluded());
                    scmCustomerQuotes.setDisposableQuantity(tempQuote.getDisposableQuantity());
                    scmCustomerQuotes.setDisposableUnit(tempQuote.getDisposableUnit());
                    scmCustomerQuotes.setDisposableUnitPrice(tempQuote.getDisposableUnitPrice().multiply(convertRate));
                    scmCustomerQuotes.setTryLot(tempQuote.getTryLot());
                    scmCustomerQuotes.setTryUnit(tempQuote.getTryUnit());
                    scmCustomerQuotes.setTryUnitPrice(tempQuote.getTryUnitPrice().multiply(convertRate));
                    scmCustomerQuotes.setTryTotalPrice(tempQuote.getTryTotalPrice().multiply(convertRate));
                    scmCustomerQuotes.setMassLot(tempQuote.getMassLot());
                    scmCustomerQuotes.setMassUnit(tempQuote.getMassUnit());
                    scmCustomerQuotes.setMassUnitPrice(tempQuote.getMassUnitPrice().multiply(convertRate));
                    scmCustomerQuotes.setMoldCost(tempQuote.getMoldCost().multiply(convertRate));
                    scmCustomerQuotes.setJigCost(tempQuote.getJigCost().multiply(convertRate));
                    scmCustomerQuotes.setMoldTryingDeliveryDays(tempQuote.getMoldTryingDeliveryDays());
                    scmCustomerQuotes.setMoldLife(tempQuote.getMoldLife());
                    scmCustomerQuotes.setDisposableDeliveryDays(tempQuote.getDisposableDeliveryDays());
                    scmCustomerQuotes.setTryDeliveryDays(tempQuote.getTryDeliveryDays());
                    scmCustomerQuotes.setMassDeliveryDays(tempQuote.getMassDeliveryDays());
                    scmCustomerQuotes.setStatus(0L);
                    scmCustomerQuotes.setStatusReason(scmEstimateQuotes.getStatusReason());
                    scmCustomerQuotes.setCustomerCurrency(scmProjects.getCustomerCurrency());
                    scmCustomerQuotes.setCustomerCurrencyRate(scmProjects.getCustomerCurrencyRate());
                    scmCustomerQuotesService.insertScmCustomerQuotes(scmCustomerQuotes);
                }
//                else if (scmEstimateQuotes.getStatus() != 1){
//                    scmEstimateQuotes.setStatus(0L);
//                    scmEstimateQuotes.setStatusReason(scmEstimateQuotes.getStatusReason());
//                    scmCustomerQuotesService.updateScmCustomerQuotes(scmCustomerQuotes);
//                }
            }

            // 如果状态为2 or 3，则查询ScmEstimateQuotes中是否存在对应记录，如果存在，则修改ScmEstimateQuotes中记录状态为2 or 3
            if (scmEstimateQuotes.getStatus() == 2 || scmEstimateQuotes.getStatus() == 3){
                if (scmCustomerQuotes == null){
                    break;
                } else if (scmEstimateQuotes.getStatus() != 2 && scmEstimateQuotes.getStatus() != 3){
                    scmCustomerQuotesService.deleteScmCustomerQuotesById(scmCustomerQuotes.getId());
                }
            }
        }

        return rows;
    }
}
